<template>
  <view class="category">
    <Form class="category-form">
      <!-- 标题 -->
      <FormItem class="category-form_header">
        <view class="form-item-wrap">
          <view class="cat-item-left">
            <text class="form-label">分类名称</text>
          </view>
          <view class="cat-item-right">
            <text v-if="!isSort" class="text-btn" @click="isSort=true">排序</text>
            <text v-if="isSort" class="text-btn" @click="handleSaveSort">保存</text>
          </view>
        </view>
      </FormItem>
      <!-- 已有目录 -->
      <FormItem v-for="(item,index) in catList" :key="item.id">
        <view class="form-item-wrap">
          <view class="cat-item-left">
            <text v-if="item.editType==editType.NORMAL">{{ item.name }}</text>
            <input
              ref="modifyInput"
              v-if="item.editType==editType.MODIFY"
              v-model="updateParams.name"
              focus
              :placeholder="updateParams.placeholder"
              type="text"
            />
          </view>
          <view class="cat-item-right">
            <!-- 编辑 删除 -->
            <view v-if="!isSort&&item.editType==editType.NORMAL" class="action-wrap">
              <!-- 编辑 -->
              <text class="text-btn-grey edit-btn iconfont" @click="handleClickModify(item,index)">&#xe625;</text>
              <!-- 删除 -->
              <text class="text-btn-grey iconfont" @click="handleClickDelete(index)">&#xe641;</text>
            </view>
            <!-- 保存编辑内容 -->
            <view v-if="!isSort&&item.editType==editType.MODIFY" class="action-wrap">
              <text class="text-btn" @click="handleClickUpdate(index)">保存</text>
            </view>
            <!-- 排序上下 -->
            <view v-if="isSort" class="action-wrap">
              <SortButton :up-disabled="index==0" :down-disabled="index==catList.length-1" @up="sortUp(item,index)" @down="sortDown(item,index)" />
              <!-- <text :class="{'disabled-sort':index==0}" class="edit-btn iconfont sort-btn" @click="sortUp(item,index)">&#xe633;</text>
              <text :class="{'disabled-sort':index==catList.length-1}" class="iconfont sort-btn" @click="sortDown(item,index)">&#xe642;</text>-->
            </view>
          </view>
        </view>
      </FormItem>
      <!-- 添加新类目 -->
      <FormItem v-if="addNew&&!isSort" style="margin-bottom:20rpx">
        <view class="form-item-wrap">
          <view class="cat-item-left">
            <input v-model="newParams.name" focus type="text" placeholder="请输入分类名称" />
          </view>
          <view class="cat-item-right">
            <view class="action-wrap">
              <text class="text-btn" @click="handleClickAddCat">保存</text>
              <text class="text-btn-grey" @click="addNew=false;newParams.name = ''">取消</text>
            </view>
          </view>
        </view>
      </FormItem>
      <FormItem v-if="!addNew&&!isSort">
        <view class="form-item-wrap" @click="addNew=true">
          <view class="cat-item-left">
            <text class="text-btn">添加分类</text>
          </view>
          <view class="cat-item-right">
            <!-- <text>排序</text> -->
          </view>
        </view>
      </FormItem>
    </Form>
  </view>
</template>

<script>
import Form from "./components/Form.vue";
import FormItem from "./components/FormItem.vue";
import { EDIT_TYPE } from "../../config/consts.js";
import { mapState, mapMutations, mapActions } from "vuex";
import { Debounce } from "../../utils/index";
import SortButton from "../../components/public/SortButton/index.vue";
import { moveListItem } from "../../utils/menu";
export default {
  components: {
    Form,
    FormItem,
    SortButton
  },
  data() {
    return {
      addNew: false,
      isSort: false,
      editType: EDIT_TYPE,
      // editType: {
      //   NORMAL: "NORMAL", // 排序
      //   SORT: "SORT", // 排序
      //   ADD: "ADD", // 新建
      //   MODIFY: "MODIFY" // 修改
      // },
      newParams: {
        name: ""
      },
      updateParams: {
        name: "",
        placeholder: ""
      },
      catList: [],
      changeList: []
    };
  },
  computed: {
    ...mapState({
      list: state => state.menus.menus,
      sid: state => state.user.activeShopId
    })
  },
  created() {
    this.init();
  },
  methods: {
    ...mapActions({
      postMenuCat: "postMenuCat",
      putMenuCat: "putMenuCat",
      deleteMenuCat: "deleteMenuCat",
      putMenuCatSort: "putMenuCatSort"
    }),
    ...mapMutations({
      SET_MENUS: "SET_MENUS"
    }),
    async init() {
      this.catList = this.list.map(v => {
        return { ...v, editType: this.editType.NORMAL };
      });
    },
    // 点击保存新类目
    handleClickAddCat: Debounce(function() {
      if (this.newParams.name) {
        uni.showLoading();
        this.postMenuCat({ sid: this.sid, params: this.newParams })
          .then(res => {
            // 将新的分类加入到list中
            this.catList.push({ ...res, editType: this.editType.NORMAL });
          })
          .finally(() => {
            this.newParams.name = "";
            uni.hideLoading();
          });
      }
    }, 500),
    // 设置类型
    setEditType(index, editType) {
      this.catList[index].editType = editType;
    },
    // 点击编辑按钮
    handleClickModify(item, index) {
      this.updateParams.name = "";
      this.updateParams.placeholder = item.name;
      this.setEditType(index, this.editType.MODIFY);
    },
    // 点击保存更新
    handleClickUpdate(index) {
      let catId = this.catList[index].id;
      let form = this.updateParams;
      // 判断是否修改了值
      if (form.name || form.name === 0 || form.name === "0") {
        this.putMenuCat({
          sid: this.sid,
          catId,
          params: { name: form.name }
        }).then(res => {
          if (!res.code) {
            this.catList[index].name = form.name;
            this.setEditType(index, this.editType.NORMAL);
          } else {
            uni.showToast({ icon: "none", title: res.errMsg });
          }
        });
      } else {
        this.setEditType(index, this.editType.NORMAL);
      }
    },
    // 删除分类
    handleClickDelete(index) {
      let catId = this.catList[index].id;
      uni.showModal({
        title: "提示",
        content: "删除该分类后，此分类下的所有商品也将删除，确定删除？",
        success: res => {
          if (res.confirm) {
            uni.showLoading();
            this.deleteMenuCat({ sid: this.sid, catId })
              .then(res => {
                if (!res.code) this.catList.splice(index, 1);
                else uni.showToast({ title: res.errMsg, icon: "none" });
              })
              .finally(() => {
                uni.hideLoading();
              });
          } else if (res.cancel) {
            // console.log("用户点击取消");
          }
        }
      });
    },
    // 保存排序
    handleSaveSort() {
      let params = this.changeList.map(v => {
        return {
          catId: v.id,
          sort: v.sort
        };
      });
      uni.showLoading();
      this.putMenuCatSort(params)
        .then(res => {
          // this.SET_MENUS(this.catList);
          this.isSort = false;
          this.$toast("保存成功");
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    // 向上移动
    sortUp(item, index) {
      let changeItem = moveListItem(this.catList, index, index - 1);
      this.addChangeItem(changeItem);
    },
    // 向下移动
    sortDown(item, index) {
      let changeItem = moveListItem(this.catList, index, index + 1);
      this.addChangeItem(changeItem);
    },
    addChangeItem(item) {
      let index = this.changeList.findIndex(v => v.id == item.id);
      if (index == -1) this.changeList.push(item);
      else this.changeList[index] = item;
    }
  }
};
</script>

<style lang="scss">
@import "@/static/iconfont/iconfont.css";

page {
  background-color: $uni-bg-color-grey;
}

.category {
  .text-btn {
    color: $uni-color-primary;
  }

  .text-btn-grey {
    color: $uni-text-color-grey;
  }

  height: 100vh;

  // background-color: $uni-bg-color-grey;
  .category-form {
    // margin-top: 40rpx;
    padding-top: 100rpx;
    .category-form_header {
      position: fixed;
      top: 0;
      width: 100%;
      .form-item-wrap {
        padding-right: 30rpx;
      }
    }
  }

  .form-item-wrap {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 100%;
    .form-label {
      color: $uni-color-primary;
    }

    .action-wrap {
      text {
        margin-right: 20rpx;

        &:last-child {
          margin-right: 0;
        }
      }
      .edit-btn {
        margin-right: 40rpx;

        &:last-child {
          margin-right: 0;
        }
      }

      .sort-btn {
        color: $uni-color-primary;
        &:first-child {
          margin-right: 40rpx;
        }
        &.disabled-sort {
          color: $uni-text-color-grey;
        }
      }
    }
  }
}
</style>
